/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import entities.Keyword;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Problem;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author sbaldrich
 */
public class KeywordJpaController {

    public KeywordJpaController()
    {
        emf = Persistence.createEntityManagerFactory("CodeMastersAlphaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Keyword keyword)
    {
        if (keyword.getProblemList() == null)
        {
            keyword.setProblemList(new ArrayList<Problem>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Problem> attachedProblemList = new ArrayList<Problem>();
            for (Problem problemListProblemToAttach : keyword.getProblemList())
            {
                problemListProblemToAttach = em.getReference(problemListProblemToAttach.getClass(), problemListProblemToAttach.getIdProblem());
                attachedProblemList.add(problemListProblemToAttach);
            }
            keyword.setProblemList(attachedProblemList);
            em.persist(keyword);
            for (Problem problemListProblem : keyword.getProblemList())
            {
                problemListProblem.getKeywordList().add(keyword);
                problemListProblem = em.merge(problemListProblem);
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Keyword keyword) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Keyword persistentKeyword = em.find(Keyword.class, keyword.getIdKeyword());
            List<Problem> problemListOld = persistentKeyword.getProblemList();
            List<Problem> problemListNew = keyword.getProblemList();
            List<Problem> attachedProblemListNew = new ArrayList<Problem>();
            for (Problem problemListNewProblemToAttach : problemListNew)
            {
                problemListNewProblemToAttach = em.getReference(problemListNewProblemToAttach.getClass(), problemListNewProblemToAttach.getIdProblem());
                attachedProblemListNew.add(problemListNewProblemToAttach);
            }
            problemListNew = attachedProblemListNew;
            keyword.setProblemList(problemListNew);
            keyword = em.merge(keyword);
            for (Problem problemListOldProblem : problemListOld)
            {
                if (!problemListNew.contains(problemListOldProblem))
                {
                    problemListOldProblem.getKeywordList().remove(keyword);
                    problemListOldProblem = em.merge(problemListOldProblem);
                }
            }
            for (Problem problemListNewProblem : problemListNew)
            {
                if (!problemListOld.contains(problemListNewProblem))
                {
                    problemListNewProblem.getKeywordList().add(keyword);
                    problemListNewProblem = em.merge(problemListNewProblem);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = keyword.getIdKeyword();
                if (findKeyword(id) == null)
                {
                    throw new NonexistentEntityException("The keyword with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Keyword keyword;
            try
            {
                keyword = em.getReference(Keyword.class, id);
                keyword.getIdKeyword();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The keyword with id " + id + " no longer exists.", enfe);
            }
            List<Problem> problemList = keyword.getProblemList();
            for (Problem problemListProblem : problemList)
            {
                problemListProblem.getKeywordList().remove(keyword);
                problemListProblem = em.merge(problemListProblem);
            }
            em.remove(keyword);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Keyword> findKeywordEntities()
    {
        return findKeywordEntities(true, -1, -1);
    }

    public List<Keyword> findKeywordEntities(int maxResults, int firstResult)
    {
        return findKeywordEntities(false, maxResults, firstResult);
    }

    private List<Keyword> findKeywordEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Keyword.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Keyword findKeyword(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Keyword.class, id);
        } finally
        {
            em.close();
        }
    }
    public Keyword findKeyword(String name)
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createNamedQuery("Keyword.findByName");
            q.setParameter("name", name);
            return(Keyword)q.getSingleResult();
        } finally
        {
            em.close();
        }
    }

    public int getKeywordCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Keyword> rt = cq.from(Keyword.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

}
